package tr.muyat.kablosuzizci.istemci.yardimcilarmodulu;

import java.nio.ByteBuffer;


/**
 * Genel kullanimi olan statik donusturcu metodlari barindirir.
 * 
 *  
 * @author Dzhoshkun Ismail Shakir, Fatih Ulusoy
 */
public class Kullanislilar {

	/**
	 * {@link http://www.daniweb.com/software-development/java/code/216874/primitive-types-as-byte-arrays} adresinden esinlenilmistir.
	 * @param deger
	 * @return {@code deger}in {@code byte} dizini olarak gosterimi
	 */
	public static byte[] byteDizinineDonustur(float deger) {
		int data=Float.floatToRawIntBits(deger);
		return new byte[] {
		    (byte)((data >> 24) & 0xff),
		    (byte)((data >> 16) & 0xff),
		    (byte)((data >> 8) & 0xff),
		    (byte)((data >> 0) & 0xff),
		};
	}

	/**
	 * {@link http://www.daniweb.com/software-development/java/code/216874/primitive-types-as-byte-arrays} adresinden esinlenilmistir.
	 * @param floatByteDizini
	 * @return {@code floatByteDizini}nin {@code float} hali
	 * @throws FormatHatasi
	 */
	public static float floataDonustur(byte[] floatByteDizini) throws FormatHatasi {
		int data = (int)( // NOTE: type cast not necessary for int
	        (0xff & floatByteDizini[0]) << 24  |
	        (0xff & floatByteDizini[1]) << 16  |
	        (0xff & floatByteDizini[2]) << 8   |
	        (0xff & floatByteDizini[3]) << 0
        );
		return Float.intBitsToFloat(data);
	}
	
	/**
	 * 
	 * @param aci
	 * @return aci degeri {@code 0} ve {@code 2pi} arasindaysa {@code true},
	 * degilse {@code false}
	 */
	public static boolean aciDegeriDogruMu(float aci) {
		return aci>=(float)-2*Math.PI && aci<=(float)2*Math.PI;
	}
	
	/**
	 * Float dizisini byte dizisine donusturur.
	 * 
	 * @param inData
	 * @return
	 */
	public static byte[] byteDizisineDonustur(float[] inData) {
		int j = 0;
		int length = inData.length;
		byte[] outData = new byte[length * 4];
		for (int i = 0; i < length; i++) {
			int data = Float.floatToIntBits(inData[i]);
			outData[j++] = (byte) (data >>> 24);
			outData[j++] = (byte) (data >>> 16);
			outData[j++] = (byte) (data >>> 8);
			outData[j++] = (byte) (data >>> 0);
		}
		return outData;
	}

	/**
	 * Byte dizisini float dizisine donusturur.
	 * 
	 * @param buffer
	 * @param length
	 * @return
	 */
	public static float[] floatDizisineDonustur(byte[] buffer, int length) {

		float[] result = new float[length / 4];
		ByteBuffer buf = ByteBuffer.wrap(buffer, 0, length);
		for (int i = 0; i < length / 4; i++) {
			result[i] = buf.getFloat();
		}

		return result;
	}
	
}
